/* __auth__ : KunLin */
package com.cskaoyan.typehandler;

import com.google.gson.Gson;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
@Component
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    private Gson gson;

    @Autowired
    public void setGson(Gson gson) {
        this.gson = gson;
    }

    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] input, JdbcType jdbcType) throws SQLException {
        String s = gson.toJson(input);
        preparedStatement.setString(index, s);
    }

    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        return transfer(resultSet.getString(columnName));
    }

    @Override
    public String[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return transfer(resultSet.getString(columnIndex));
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return transfer(callableStatement.getNString(columnIndex));
    }

    private String[] transfer(String result) {
        if (result == null || "".equals(result)) {
            return new String[0];
        }
       return gson.fromJson(result, String[].class);
    }
}
